<template>
  <div class="ai-chat-page">
    <van-nav-bar
      title="AI助手"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    >
      <template #right>
        <van-icon name="clock" @click="showHistory = true" />
      </template>
    </van-nav-bar>
    
    <div class="chat-container">
      <div class="chat-messages" ref="messagesContainer">
        <!-- 欢迎消息 -->
        <div class="message system-message">
          <div class="message-content">
            <p>你好！我是你的编码助手</p>
          </div>
        </div>
        
        <!-- 聊天消息 -->
        <div 
          v-for="(message, index) in messages" 
          :key="index" 
          :class="['message', message.role === 'user' ? 'user-message' : 'ai-message']"
        >
          <template v-if="message.role === 'assistant'">
            <div class="message-avatar">
              <van-icon name="manager" size="20" />
            </div>
            <div class="message-content">
              <p v-html="message.content"></p>
              <div v-if="message.showLoadingState" class="typing-dots">
                <span></span><span></span><span></span>
              </div>
            </div>
          </template>
          <template v-else>
            <div class="message-content">
              <p v-html="message.content"></p>
            </div>
            <div class="message-avatar">
              <van-icon name="contact" size="20" />
            </div>
          </template>
        </div>
      </div>
      
      <div class="chat-input-container">
        <!-- 快捷操作选项移到这里 -->
        <div class="quick-actions">
          <div 
            v-for="(action, index) in quickActions" 
            :key="index"
            class="quick-action-item" 
            @click="useQuickPrompt(action.prompt)"
          >
            <span>{{ action.label }}</span>
          </div>
        </div>

        <div class="chat-input-wrapper">
          <van-field
            v-model="inputMessage"
            type="textarea"
            placeholder="输入消息..."
            rows="1"
            autosize
            class="chat-input"
            @keypress.enter.prevent="sendMessage"
          />
          <template v-if="loading">
            <van-button 
              type="danger" 
              size="small" 
              class="send-button stop-button"
              @click="stopChat"
            >
              <van-icon name="cross" class="stop-icon" />
              <span>停止</span>
            </van-button>
          </template>
          <template v-else>
            <van-button 
              type="primary" 
              size="small" 
              class="send-button" 
              :loading="loading"
              :disabled="!inputMessage.trim()"
              @click="sendMessage"
            >
              <van-icon name="guide" class="send-icon" />
              <span>发送</span>
            </van-button>
          </template>
        </div>
      </div>
    </div>

    <!-- 历史会话弹出层 -->
    <van-popup
      v-model:show="showHistory"
      position="right"
      :style="{ height: '100%', width: '80%' }"
    >
      <div class="history-panel">
        <div class="history-header">
          <span>历史会话</span>
          <div class="header-actions">
            <van-button type="primary" size="small" @click="createNewSession">新会话</van-button>
            <van-icon name="cross" @click="showHistory = false" />
          </div>
        </div>
        <div class="history-list">
          <div 
            v-for="(session, index) in chatHistory" 
            :key="index" 
            class="history-item"
            @click="loadHistorySession(session)"
          >
            <div class="history-title">
              <span class="history-index">#{{ chatHistory.length - index }}</span>
              <span class="history-description">{{ getHistoryTitle(session) }}</span>
            </div>
            <div class="history-time">{{ formatTime(session.timestamp) }}</div>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast } from 'vant'
import { createChatMessage } from '@/api/dify'

const route = useRoute()
const router = useRouter()
const messagesContainer = ref(null)
const inputMessage = ref('')
const messages = ref([])
const loading = ref(false)
const conversationId = ref(null)
const showHistory = ref(false)
const chatHistory = ref([])

// 快捷操作选项
const quickActions = [
  { label: '自我介绍', prompt: '介绍一下你自己' },
  { label: '画图', prompt: '你能画图吗' },
  { label: '天气查询', prompt: '今天天气怎么样？' },
  { label: '笑话', prompt: '给我讲个笑话' }
]

const onClickLeft = () => {
  router.back()
}

// 发送消息
const sendMessage = async () => {
  const message = inputMessage.value.trim()
  if (!message || loading.value) return
  
  // 添加用户消息
  messages.value.push({
    role: 'user',
    content: message
  })
  
  inputMessage.value = ''
  await scrollToBottom()
  
  try {
    loading.value = true
    
    // 创建AI消息占位
    const aiMessage = {
      role: 'assistant',
      content: '',
      showLoadingState: true
    }
    messages.value.push(aiMessage)
    await scrollToBottom()
    
    await createChatMessage(message, conversationId.value, [], (data) => {
      if (data.conversation_id && !conversationId.value) {
        // 保存新的会话ID
        conversationId.value = data.conversation_id
      }
      
      // 处理消息事件
      if (data.event === 'message_replace' || data.event === 'agent_message') {
        aiMessage.content = data.answer
        scrollToBottom()
      } else if (data.event === 'message_end') {
        aiMessage.content = data.answer || aiMessage.content
        scrollToBottom()
        // 保存当前会话
        saveCurrentSession()
      }
    })
  } catch (err) {
    const errorMessage = err.message.includes('当前对话尚未完成') 
      ? '请等待当前对话完成' 
      : 'AI助手遇到了问题，请稍后再试'
    
    messages.value.pop() // 移除助手的消息
    messages.value.push({
      role: 'assistant',
      content: errorMessage,
    })
  } finally {
    loading.value = false
    await scrollToBottom()
  }
}

// 停止对话
const stopChat = () => {
  loading.value = false
  const lastMessage = messages.value[messages.value.length - 1]
  if (lastMessage && lastMessage.role === 'assistant') {
    lastMessage.showLoadingState = false // 确保移除loading状态
    lastMessage.content = lastMessage.content || '对话已终止'
    saveCurrentSession()
  }
}

// 使用快捷提示
const useQuickPrompt = (prompt) => {
  // 如果是聊天帮助选项，只显示欢迎消息
  if (prompt === '你好，我是你的AI助手，有什么可以帮你的吗？') {
    messages.value.push({
      role: 'assistant',
      content: prompt,
      showLoadingState: false
    })
    return
  }
  
  // 其他选项直接发送消息
  inputMessage.value = prompt
  sendMessage()
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 监听消息变化，自动滚动到底部
watch(messages, () => {
  scrollToBottom()
})

onMounted(() => {
  const preset = route.query.preset
  if (preset) {
    inputMessage.value = preset
    // 如果有预设消息，自动发送
    nextTick(() => {
      sendMessage()
    })
  }
  
  // 加载历史记录
  try {
    const savedHistory = localStorage.getItem('chat-history');
    if (savedHistory) {
      chatHistory.value = JSON.parse(savedHistory);
    }
  } catch (e) {
    console.error('恢复历史会话失败:', e);
  }
  
  scrollToBottom()
})

// 创建新会话
const createNewSession = () => {
  conversationId.value = null
  messages.value = []
  showHistory.value = false
}

// 加载历史会话
const loadHistorySession = (session) => {
  conversationId.value = session.conversation_id
  messages.value = session.messages
  showHistory.value = false
}

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`
}

// 保存当前会话
const saveCurrentSession = () => {
  if (messages.value.length > 1) { // 至少有一问一答才保存
    const timestamp = Date.now();
    const chatSession = {
      id: timestamp,
      timestamp,
      conversation_id: conversationId.value,
      messages: [...messages.value]
    };
    
    // 从本地存储获取现有历史
    let history = [];
    try {
      const savedHistory = localStorage.getItem('chat-history');
      if (savedHistory) {
        history = JSON.parse(savedHistory);
      }
    } catch (e) {
      console.error('读取历史失败:', e);
    }
    
    // 添加新会话到历史
    history.unshift(chatSession);
    
    // 限制历史记录数量（保留最新的20条）
    if (history.length > 20) {
      history = history.slice(0, 20);
    }
    
    // 保存到本地存储
    localStorage.setItem('chat-history', JSON.stringify(history));
    chatHistory.value = history;
  }
}

// 获取历史会话的标题
const getHistoryTitle = (session) => {
  // 找到第一条用户消息
  const firstUserMessage = session.messages.find(msg => msg.role === 'user')
  return firstUserMessage ? 
    (firstUserMessage.content.length > 20 ? 
      firstUserMessage.content.substring(0, 20) + '...' : 
      firstUserMessage.content) : 
    '新会话'
}
</script>

<style lang="scss" scoped>
.ai-chat-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: var(--background-color);
  
  .chat-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    height: calc(100vh - 46px);
    
    .chat-messages {
      flex: 1;
      overflow-y: auto;
      padding: 16px;
      padding-bottom: 160px; // 增加底部内边距，防止消息被遮挡
      
      .message {
        display: flex;
        margin-bottom: 16px;
        
        .message-avatar {
          width: 36px;
          height: 36px;
          border-radius: 50%;
          background-color: var(--background-color-light);
          display: flex;
          justify-content: center;
          align-items: center;
          flex-shrink: 0;
        }
        
        .message-content {
          position: relative;
          max-width: 70%;
          padding: 12px;
          border-radius: 12px;
          margin: 0 12px;
          
          p {
            margin: 0;
            line-height: 1.5;
            word-break: break-word;
          }
          
          .typing-dots {
            display: inline-flex;
            align-items: center;
            padding: 4px 8px;
            
            span {
              display: inline-block;
              width: 4px;
              height: 4px;
              margin: 0 1px;
              background-color: var(--text-color-secondary);
              border-radius: 50%;
              animation: bounce 1.4s infinite ease-in-out;
              
              &:nth-child(1) { animation-delay: -0.32s; }
              &:nth-child(2) { animation-delay: -0.16s; }
              &:nth-child(3) { animation-delay: 0s; }
            }
          }
        }
        
        &.system-message {
          justify-content: center;
          
          .message-content {
            background-color: var(--background-color-light);
            color: var(--text-color-secondary);
            font-size: 14px;
            padding: 8px 16px;
            border-radius: 16px;
          }
        }
        
        &.user-message {
          justify-content: flex-end;
          
          .message-content {
            background-color: var(--primary-color);
            color: #fff;
          }
        }
        
        &.ai-message {
          justify-content: flex-start;
          
          .message-content {
            background-color: var(--background-color-light);
          }
        }
      }
    }
    
    .chat-input-container {
      position: fixed;
      left: 0;
      right: 0;
      bottom: calc(var(--tabbar-height) + env(safe-area-inset-bottom));
      padding: 12px 16px;
      background-color: var(--background-color);
      border-top: 1px solid var(--border-color-light);
      z-index: 999;
      
      .quick-actions {
        display: flex;
        overflow-x: auto;
        margin-bottom: 8px;
        padding-bottom: 4px;
        -webkit-overflow-scrolling: touch;
        
        &::-webkit-scrollbar {
          display: none;
        }
        
        .quick-action-item {
          flex-shrink: 0;
          padding: 6px 12px;
          background-color: var(--background-color-light);
          border-radius: 12px;
          margin-right: 8px;
          font-size: 13px;
          color: var(--text-color);
          white-space: nowrap;
          transition: all 0.2s ease;
          box-shadow: 0 2px 4px rgba(0,0,0,0.04);
          
          &:active {
            transform: scale(0.95);
            background-color: var(--primary-color-light);
          }
        }
      }
      
      .chat-input-wrapper {
        display: flex;
        align-items: center; // 改为居中对齐
        background-color: var(--background-color-light);
        border-radius: 20px;
        padding: 4px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.06);
        
        .chat-input {
          flex: 1;
          background: transparent;
          
          :deep(.van-field__control) {
            min-height: 20px;
            height: 15px; // 设置固定高度，与按钮一致
            padding: 4px 8px;
            font-size: 14px;
            line-height: 10px; // 调整行高
            resize: none;
          }
        }
        
        .send-button {
          height: 32px;
          min-width: 64px;
          border-radius: 16px;
          margin-left: 8px;
          padding: 0 12px;
          font-size: 14px;
          
          .send-icon, .stop-icon {
            font-size: 16px;
            margin-right: 4px;
          }
          
          &.stop-button {
            background-color: #ff4444;
            border-color: #ff4444;
            
            &:active {
              background-color: #ee3333;
              border-color: #ee3333;
            }
          }
          
          &:not(:disabled):active {
            transform: scale(0.96);
          }
        }
      }
    }
  }

  .history-panel {
    display: flex;
    flex-direction: column;
    height: 100%;
    padding: 16px;
    background-color: var(--background-color);
    
    .history-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-bottom: 16px;
      border-bottom: 1px solid var(--border-color-light);
      
      span {
        font-size: 16px;
        font-weight: bold;
      }
      
      .header-actions {
        display: flex;
        align-items: center;
        
        .van-button {
          margin-right: 8px;
        }
      }
    }
    
    .history-list {
      flex: 1;
      overflow-y: auto;
      margin-top: 16px;
      
      .history-item {
        display: flex;
        flex-direction: column;
        padding: 12px;
        background-color: var(--background-color-light);
        border-radius: 8px;
        margin-bottom: 8px;
        cursor: pointer;
        transition: all 0.3s ease;
        
        &:hover {
          background-color: var(--background-color);
          transform: translateY(-1px);
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
        
        .history-title {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 4px;
          
          .history-index {
            color: var(--primary-color);
            font-weight: bold;
            font-size: 14px;
          }
          
          .history-description {
            color: var(--text-color);
            font-size: 14px;
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
        
        .history-time {
          font-size: 12px;
          color: var(--text-color-secondary);
        }
      }
    }
  }
}

@keyframes bounce {
  0%, 80%, 100% { transform: scale(0); }
  40% { transform: scale(1); }
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}
</style>